<template>
  <div class="center-block">
    <!-- ---------------------包装袋配置------------------------ -->
    <div class="package-edit" v-show="editType == 'package'">
      <div
        class="scale-block"
        :style="{
          transform: `scale(${packageConfig.scale / 100})`,
        }"
      >
        <div :style="canvasStyle2" class="canvas" ref="packageFrontRef">
          <div class="tip">{{ $t("editFormula.front") }}</div>
          <DragBlock
            side="0"
            className="package"
            @drop="dragHandle"
            @dragover="dragoverHandle"
            @mousedown="packageClick"
            :component="packageFront"
            shapeType="package"
            :style="packageStyle(0)"
            elId="package-front"
          >
            <img
              src="@/assets/images/edit/esd.png"
              class="esd-img"
              :style="esdStyle"
              v-show="packageConfig.hasESD && packageConfig.esdSizeInBag == 0"
            />
          </DragBlock>
        </div>
        <div :style="canvasStyle2" class="canvas" ref="packageOppositeRef">
          <div class="tip">{{ $t("editFormula.opposite") }}</div>
          <DragBlock
            side="1"
            className="package"
            @drop="dragHandle"
            @dragover="dragoverHandle"
            @mousedown="packageClick"
            :component="packageOpposite"
            shapeType="package"
            :style="packageStyle(1)"
            elId="package-opposite"
          >
            <img
              src="@/assets/images/edit/esd.png"
              class="esd-img"
              :style="esdStyle"
              v-show="packageConfig.hasESD && packageConfig.esdSizeInBag == 1"
            />
          </DragBlock>
        </div>
      </div>
    </div>
    <!-- ---------------------卷盘配置------------------------ -->
    <div class="reel-edit" ref="contentRef" v-show="editType == 'reel'">
      <div
        class="scale-block"
        :style="{
          transform: `scale(${reelConfig.scale / 100})`,
        }"
      >
        <DragBlock
          side="0"
          className="canvas"
          @drop="dragHandle"
          @dragover="dragoverHandle"
          @mousedown="clickHandle"
          :component="frontComponent"
          shapeType="reel"
          :style="canvasStyle"
          elId="reel-front"
        >
          <div>
            <div class="tip">{{ $t("editFormula.front") }}</div>
            <div class="x-line"></div>
            <div class="y-line"></div>
            <div class="reel" :style="reelStyle(0)"></div>
          </div>
        </DragBlock>
        <DragBlock
          side="1"
          className="canvas opposite"
          @drop="dragHandle"
          @dragover="dragoverHandle"
          @mousedown="clickHandle"
          :component="oppositeComponent"
          shapeType="reel"
          :style="canvasStyle"
          elId="reel-opposite"
        >
          <div>
            <div class="tip">{{ $t("editFormula.opposite") }}</div>
            <div class="x-line"></div>
            <div class="y-line"></div>
            <div class="reel" :style="reelStyle(1)"></div>
          </div>
        </DragBlock>
      </div>
    </div>
    <!-- ---------------------内盒配置------------------------ -->
    <innerBoxEdit v-show="editType == 'innerBox'"></innerBoxEdit>
    <!-- ---------------------底部工具栏------------------------ -->
    <div class="footer">
      <div class="right">
        <el-icon @click="lockHandle">
          <Lock v-if="editCanvas.lockScale" />
          <Unlock v-else />
        </el-icon>
        <template v-if="editType == 'reel'">
          <el-slider
            v-model="reelConfig.scale"
            :min="50"
            :max="300"
            :disabled="editCanvas.lockScale"
          />
          <el-select
            v-model="reelConfig.scale"
            class="sf-select"
            size="small"
            :disabled="editCanvas.lockScale"
          >
            <el-option
              v-for="item in scaleType"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </template>
        <template v-if="editType == 'package'">
          <el-slider
            v-model="packageConfig.scale"
            :min="50"
            :max="300"
            :disabled="editCanvas.lockScale"
          />
          <el-select
            v-model="packageConfig.scale"
            class="sf-select"
            size="small"
            :disabled="editCanvas.lockScale"
          >
            <el-option
              v-for="item in scaleType"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </template>
        <template v-if="editType == 'innerBox'">
          <el-slider
            v-model="innerBox.scale"
            :min="50"
            :max="300"
            :disabled="editCanvas.lockScale"
          />
          <el-select
            v-model="innerBox.scale"
            class="sf-select"
            size="small"
            :disabled="editCanvas.lockScale"
          >
            <el-option
              v-for="item in scaleType"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </template>
      </div>
    </div>
    <!-- ---------------------侧边工具栏------------------------ -->
    <div class="export-tool">
      <el-tooltip
        v-for="(item, index) of exportTool"
        :key="index"
        class="tip-item"
        effect="dark"
        :content="item.name"
        placement="left"
      >
        <template v-if="item.event == 'import'">
          <el-upload
            :show-file-list="false"
            :auto-upload="false"
            action="#"
            :on-change="handleChange"
          >
            <div class="i-box" @click="handleTool(item.event)">
              <img :src="item.img" alt="" class="img" />
            </div>
          </el-upload>
        </template>
        <template v-else>
          <div class="i-box" @click="handleTool(item.event)">
            <img :src="item.img" alt="" class="img" />
          </div>
        </template>
      </el-tooltip>
    </div>
  </div>
</template>
<script setup>
import {
  computed,
  watch,
  ref,
  reactive,
  createApp,
  onMounted,
  onBeforeUnmount,
} from "vue";
import editStore from "@/store/editStore.js";
import { Unlock, Lock } from "@element-plus/icons-vue";
import exportImg from "@/assets/images/common/export.png";
import importImg from "@/assets/images/common/import.png";
import eImg from "@/assets/images/common/e-img.png";
import exportPdf from "./component/exportPdf.vue";
import { canvasCut } from "@/utils";
import { getGUID } from "@/utils";
import { useI18n } from "vue-i18n";
import DragBlock from "./component/dragBlock.vue";
import innerBoxEdit from "./component/innerBoxEdit.vue";
import reelFrontImg from "@/assets/images/edit/reel.png";
import reelOppositeImg from "@/assets/images/edit/reel-opp.png";
import pkgImg from "@/assets/images/edit/package.png";
import useExcel from "@/hooks/useExcel";

const { t: $t } = useI18n();
const store = editStore();

let scaleType = [50, 80, 100, 120, 150, 200, 250, 300];
let exportTool = [
  {
    name: "导出json数据",
    img: exportImg,
    event: "export",
  },
  {
    name: "导入EXCEL数据",
    img: importImg,
    event: "import",
  },
  // {
  //   name: "导出图片",
  //   img: eImg,
  //   event: "exportPdf",
  // },
];

let contentRef = ref();
let packageOppositeRef = ref();
let packageFrontRef = ref();

let reelConfig = computed(() => store.reelConfig);
let packageConfig = computed(() => store.packageConfig);
let innerBox = computed(() => store.innerBox);
let editType = computed(() => store.editType);
let editCanvas = computed(() => store.editCanvas);
let currentReel = computed(() => store.getCurrentReel);
let oppositeComponent = computed(() => store.getCurrenttOppositeReel);
let frontComponent = computed(() => store.getCurrentFrontReel);
let packageFront = computed(() => store.getCurrentPackage.frontComponentList);
let packageOpposite = computed(
  () => store.getCurrentPackage.oppositeComponentList
);
let reelStyle = computed(() => (t) => {
  let reelConfig = store.reelConfig;
  let backgroundImage = "";
  if (t == 0) {
    //正面
    backgroundImage = reelConfig.frontImg
      ? `url(${reelConfig.frontImg})`
      : `url(${reelFrontImg})`;
  } else {
    backgroundImage = reelConfig.oppositeImg
      ? `url(${reelConfig.oppositeImg})`
      : `url(${reelOppositeImg})`;
  }
  return {
    backgroundImage,
    width: reelConfig.reelDiameter + "px",
    height: reelConfig.reelDiameter + "px",
    backgroundSize: "cover",
  };
});
let packageStyle = computed(() => (t) => {
  let packageConfig = store.packageConfig;
  let backgroundImage = "";
  if (t == 0) {
    //正面
    backgroundImage = packageConfig.frontImg
      ? `url(${packageConfig.frontImg})`
      : `url(${pkgImg})`;
  } else {
    backgroundImage = packageConfig.oppositeImg
      ? `url(${packageConfig.oppositeImg})`
      : `url(${pkgImg})`;
  }
  return {
    width: packageConfig.bagWidth + "px",
    height: packageConfig.bagHeigh + "px",
    backgroundImage,
  };
});
let canvasStyle = computed(() => {
  let reelConfig = store.getReelBlockSize;
  return {
    width: reelConfig.width + "px",
    height: reelConfig.height + "px",
  };
});
let canvasStyle2 = computed(() => {
  let packageConfig = store.getPackageBlockSize;
  return {
    width: packageConfig.width + "px",
    height: packageConfig.height + "px",
  };
});
let esdStyle = computed(() => {
  return {
    width: (store.packageConfig.esdSize || 60) + "px",
    height: (store.packageConfig.esdSize || 60) + "px",
    left: store.packageConfig.esdPositionX + "px",
    top: store.packageConfig.esdPositionY + "px",
    transform: `rotate(${store.packageConfig.esdPositionR}deg)`,
  };
});

const drag_key = "drag_key";
function dragHandle(e, side) {
  let drayDataString = e.dataTransfer.getData(drag_key);
  if (!drayDataString) return;
  let { offsetX, offsetY } = e;
  let materia = JSON.parse(drayDataString);
  materia.id = getGUID();
  let reelBlock = store.getReelBlockSize;
  let correctX = editType.value == "reel" ? reelBlock.width / 2 : 0;
  let correctY = editType.value == "reel" ? reelBlock.height / 2 : 0;
  materia.x = +(offsetX - correctX).toFixed(2);
  materia.y = +(offsetY - correctY).toFixed(2);
  materia.position = side;
  //盘袋盒箱 0-其他 1-盘 2-袋 3-盒 4-箱
  if (editType.value == "reel") {
    materia.reelType = 1;
  } else if (editType.value == "package") {
    materia.reelType = 2;
  }
  store.addComponent(materia, side);
  store.changeSelectedComponent(materia);
}

function dragoverHandle(e) {
  e.preventDefault();
  e.stopPropagation();
  if (e.dataTransfer) e.dataTransfer.dropEffect = "copy";
}

function clickHandle() {
  store.changeSelectedComponent({});
}

function packageClick() {
  store.changeSelectedComponent({ id: "package", type: "Package" });
}

function lockHandle() {
  store.editCanvas.lockScale = !store.editCanvas.lockScale;
}

function handleTool(event) {
  switch (event) {
    case "export":
      store.exportConfig();
      break;
    case "import":
      // store.importConfig();
      // importExcel();
      break;
    case "exportPdf":
      toPDF();
      break;
    default:
      break;
  }
}

function handleChange(response, uploadFile) {
  let raw = response.raw;
  if (!/(xls|xlsx)$/.test(raw.name)) {
    ElMessage.error("请导入excel文件");
    return false;
  }
  ElMessageBox.confirm(
    `导入将覆盖原页面数据,是否继续导入！\r\n该操作只会读取单文件或表格的第一个配方数据`,
    "提示",
    {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(async () => {
      let data = await useExcel(response, uploadFile);

      if (Array.isArray(data) && data[0]) {
        // store.$reset();
        store.$state = data[0];
      }
    })
    .catch((e) => {});
}

async function toPDF() {
  let div = document.createElement("div");
  createApp(exportPdf).mount(div);
  contentRef.value.appendChild(div);
  // contentRef.value.style.overflow = "scroll";
  // div.scrollIntoView({ block: "end", inline: "nearest" });
  canvasCut(contentRef.value);
  canvasCut(div);

  contentRef.value.removeChild(div);
}

function scaleSolide(e) {
  e.preventDefault();
  if (store.editCanvas.lockScale) return;
  if (e.ctrlKey) {
    let length = -e.deltaY / 10;
    if (editType.value == "reel") {
      reelConfig.value.scale += length;
    } else if (editType.value == "package") {
      packageConfig.value.scale += length;
    } else if ((editType.value = "innerBox")) {
      innerBox.value.scale += length;
    }
  }
}

onMounted(() => {
  document.body.addEventListener("wheel", scaleSolide);
});

onBeforeUnmount(() => {
  document.body.removeEventListener("wheel", scaleSolide);
});
</script>
<style scoped lang="scss">
.center-block {
  width: 100%;
  height: 100%;
  display: flex;
  position: relative;
  flex-direction: column;
  // background-color: rgb(239 239 239 / 20%);

  .package-edit {
    flex: 1;
    overflow: auto;
    .package {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translateX(-50%) translateY(-50%);
      // background-color: #403dea;
      z-index: 0;
      //background-image: url("../../../assets/images/edit/package.png");
      background-size: cover;
      border: 1px solid #fff;
    }
  }
  .reel-edit {
    flex: 1;
    overflow: auto;

    .reel {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translateX(-50%) translateY(-50%);
      // background-color: #403dea;
      z-index: 1;
      //background-image: url("../../../assets/images/edit/reel.png");
      background-size: cover;
    }
    .opposite {
      margin-top: 80px;
      .reel {
        //background-image: url("../../../assets/images/edit/reel-opp.png");
      }
    }
  }
  .canvas {
    background-color: rgba(214, 220, 242, 0.4);
    // margin-top: 10px;
    // margin-left: 80px;
    // transform-origin: 80px 10px;
    position: relative;
    margin: 10px 20px 80px 80px;
    .tip {
      position: absolute;
      top: 5px;
      left: 5px;
      color: #000;
      font-size: 16px;
      font-weight: bold;
    }
    .x-line {
      width: 1px;
      height: 100%;
      background-color: #fff;
      position: absolute;
      top: 0;
      left: 50%;
      transform: translateX(-50%);
      z-index: 999;
      pointer-events: none;
    }
    .y-line {
      width: 100%;
      height: 1px;
      background-color: #fff;
      position: absolute;
      top: 50%;
      left: 0;
      transform: translateY(-50%);
      z-index: 999;
      pointer-events: none;
    }
  }
  .scale-block {
    overflow: auto;
    transform-origin: 0 0;
  }
  .footer {
    width: 100%;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding: 0 10px;
    border-top: 1px solid #d6dcf2;
    :deep(.el-select__placeholder) {
      color: #444;
    }
    .right {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      .sf-select {
        width: 80px;
        background: transparent;
        color: #fff;
      }
      .icon {
        display: flex;
        align-items: center;
      }
      :deep(.el-slider) {
        margin: 0 10px;
        width: 200px;
        --el-slider-button-size: 15px;
      }
    }
    .nav {
      display: flex;
      border-radius: 4px;
      font-size: 14px;
      background-color: #d9d9d9;
      .nav-item {
        min-width: 50px;
        height: 30px;
        line-height: 30px;
        text-align: center;
        padding: 0 10px;
        cursor: pointer;
        &:hover {
          color: #0084fe;
          background-color: #d3eafe;
        }
      }
    }
  }
  .toggle {
    position: absolute;
    top: 10px;
    right: 10px;
    .nav-item {
      width: 80px;
    }
  }

  .export-tool {
    position: absolute;
    right: 10px;
    bottom: 100px;
    z-index: 2;
    width: 40px;
    background: #d9d9d9;
    border-radius: 24px;
    padding: 5px 0;
    display: flex;
    flex-direction: column;
    .i-box {
      width: 36px;
      height: 36px;
      margin: 0 auto;
      border-radius: 50%;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-bottom: 5px;
      .img {
        width: 24px;
        height: 24px;
      }
      &:hover {
        background: #0084fe;
      }
    }
  }
}
.esd-img {
  position: absolute;
  // width: 60px;
  // height: 60px;
}
</style>
